library(data.table); library(tidyverse); library(zoo); library(readxl)
library(ggthemes); library(scales); library(gridExtra); library(ggrepel)


#----------------------------------------------------------------------------#
# Data -------------------------------------------------------------
#----------------------------------------------------------------------------#

topic_list = c('War')
topic_names = c('War')


#---------------------#
# narratives ----#
#---------------------#

tb = read_excel('input/top articles per topic.xlsx') %>%
  mutate(
    ym = as.Date(as.yearmon(ym)),
    title_n = paste(format(ym, '(%Y/%m)'), str_squish(title))
  )


dt = readRDS('input/combined_data.rds')[['base']] %>%
  select(ym, War) %>%
  mutate(
    ym = as.Date(as.yearmon(ym)),
    War = (War - mean(War))*100
  ) %>%
  filter(year(ym) >= 1990) %>%
  pivot_longer(
    cols = !ym,
    names_to = 'topic',
    values_to = 'value'
  ) %>%
  left_join(tb, by = c('ym','topic'))



#---------------------#
# recession -----#
#---------------------#

recess = read_excel('input/us recession dummy.xlsx') %>% 
  mutate(
    date = as.Date(as.yearmon(ym)),
    xmin = date,
    xmax = lead(date),
    ymin = -100,
    ymax = 100
  ) %>% 
  filter(as.yearmon(date) >= 'Jan 1871')



#----------------------------------------------------------------------------#
# Plot -------------------------------------------------------------
#----------------------------------------------------------------------------#

plot_topic = function(){

  gplot = ggplot(data = dt, aes(x = ym, y = value)) +

    geom_rect(
      data = recess, aes(xmin = xmin, xmax = xmax, ymin = ymin, ymax = ymax, fill = as.factor(recess)), 
      inherit.aes = FALSE, alpha = 1
    ) +
    scale_fill_manual(values = c('white', 'grey')) +
    
    geom_line(size = 0.8) +
    
    labs(title = 'War', y = '', x = '') +
    
    coord_cartesian(
      expand = FALSE, # this is important
      xlim = as.Date(c('1990-01-01', '2019-12-31')),
      ylim = c(-5, 10),
      ) +
    
    scale_y_continuous(breaks = pretty_breaks()) +
    scale_x_date(
      date_breaks = '2 years', date_labels = '%Y'
      ) +
    
    geom_label_repel(
      aes(label = title_n),
          size = 5.5,
          max.overlaps = 50
    ) +
                   
    theme_base() +
    theme(
      legend.position = 'none',
      text            = element_text(size=25),
      plot.title      = element_text(hjust = 0.5),
      plot.margin     = unit(c(0,0,-0.5,0), 'pt'),
      plot.background = element_rect(colour = NA)
   )
  
  return(gplot)  
}


gplot = plot_topic()
ggsave('output/figures/Figure_4.tiff', gplot, width=18, height=12, device='tiff', dpi=300)

